import { Table, Transfer, Button, Modal, Form, Input, Upload } from 'antd';
import type { ColumnsType, TableRowSelection } from 'antd/es/table/interface';
import type { TransferItem, TransferProps } from 'antd/es/transfer';
import difference from 'lodash/difference';
import React, { useState, useEffect } from 'react';
import "./index.less"
interface RecordType {
    key: string;
    title: string;
}

interface DataType {
    title: string;
    tag: string;
    description: string;
}

interface TableTransferProps extends TransferProps<TransferItem> {
    dataSource: DataType[];
    leftColumns: ColumnsType<DataType>;
    rightColumns: ColumnsType<DataType>;
}

// Customize Table Transfer
const TableTransfer = ({ leftColumns, rightColumns, ...restProps }: TableTransferProps) => (
    <Transfer {...restProps}>
        {({
            direction,
            filteredItems,
            onItemSelectAll,
            onItemSelect,
            selectedKeys: listSelectedKeys,
            disabled: listDisabled,
        }) => {
            const columns: any = direction === 'left' ? leftColumns : rightColumns;

            const rowSelection: TableRowSelection<TransferItem> = {
                getCheckboxProps: item => ({ disabled: listDisabled || item.disabled }),
                onSelectAll(selected, selectedRows) {
                    const treeSelectedKeys = selectedRows
                        .filter(item => !item.disabled)
                        .map(({ key }) => key);
                    const diffKeys = selected
                        ? difference(treeSelectedKeys, listSelectedKeys)
                        : difference(listSelectedKeys, treeSelectedKeys);
                    onItemSelectAll(diffKeys as string[], selected);
                },
                onSelect({ key }, selected) {
                    onItemSelect(key as string, selected);
                },
                selectedRowKeys: listSelectedKeys,
            };

            return (
                <Table
                    rowSelection={rowSelection}
                    columns={columns}
                    dataSource={filteredItems}
                    size="small"
                    style={{ pointerEvents: listDisabled ? 'none' : undefined }}
                    onRow={({ key, disabled: itemDisabled }) => ({
                        onClick: () => {
                            if (itemDisabled || listDisabled) return;
                            onItemSelect(key as string, !listSelectedKeys.includes(key as string));
                        },
                    })}
                />
            );
        }}
    </Transfer>
);

const mockData = [
    {
        key: 1,
        title: {
            imgUrl: "http://cmb.beyondsofthz.com/campus/image/991344856418881536.jpg",
            imgKey: "991345374016966656.jpg",
            name: "运营位名称1",
            link: "www.baidu.com"
        }
    },
    {
        key: 2,
        title: {
            imgUrl: "http://cmb.beyondsofthz.com/campus/image/991344856418881536.jpg",
            imgKey: "991345374016966656.jpg",
            name: "运营位名称2",
            link: "www.baidu.com"
        }
    },
    {
        key: 3,
        title: {
            imgUrl: "http://cmb.beyondsofthz.com/campus/image/991344856418881536.jpg",
            imgKey: "991345374016966656.jpg",
            name: "运营位名称3",
            link: "www.baidu.com"
        }
    },
    {
        key: 5,
        title: {
            imgUrl: "http://cmb.beyondsofthz.com/campus/image/991344856418881536.jpg",
            imgKey: "991345374016966656.jpg",
            name: "运营位名称5",
            link: "www.baidu.com"
        }
    },
]





const App: React.FC = () => {
    const originTargetKeys = mockData.filter(item => Number(item.key) % 3 > 1).map(item => item.key);
    const [data, setData] = useState<any>()
    const [isEdit, setIsedit] = useState(false)
    const [iskey, setIsKey] = useState()
    const leftTableColumns: ColumnsType<DataType> = [
        {
            dataIndex: 'title',
            title: '运营位图片',
            render: (a, b) => {
                return (
                    <>
                        <div style={{ display: "flex" }}>
                            <div style={{ width: "80px", height: "50px" }}>
                                <img style={{ width: "100%", height: "100%" }} src={a.imgUrl} alt="" />
                            </div>
                            <div style={{ marginLeft: "30px" }}>
                                <h4>{a.name}</h4>
                                <p style={{ color: "#ccc", fontSize: "12px" }}>落地链接：{a.link}</p>
                            </div>
                        </div>
                    </>
                )
            }
        },
        {
            dataIndex: 'handle',
            title: '操作',
            render: (a, b) => {
                return (
                    <>
                        <p style={{ color: 'skyblue' }}>
                            <span style={{ cursor: "pointer" }} onClick={() => { edit(a, b) }}>修改</span> &nbsp;
                            <span style={{ cursor: "pointer" }} onClick={() => { del(a, b) }}> 删除</span>
                        </p>
                    </>
                )
            }
        },
    ];
    const rightTableColumns: ColumnsType<Pick<DataType, 'title'>> = [
        {
            dataIndex: 'title',
            title: '运营位图片',
            render: (a, b) => {
                return (
                    <>
                        <div style={{ display: "flex" }}>
                            <div style={{ width: "80px", height: "50px" }}>
                                <img style={{ width: "100%", height: "100%" }} src={a.imgUrl} alt="" />
                            </div>
                            <div style={{ marginLeft: "30px" }}>
                                <h4>{a.name}</h4>
                                <p style={{ color: "#ccc", fontSize: "12px" }}>落地链接：{a.link}</p>
                            </div>
                        </div>
                    </>
                )
            }
        },
        {
            dataIndex: 'handle',
            title: '操作',
            render: (a, b, index) => {
                return (
                    <>
                        <p style={{ color: 'skyblue' }}>
                            {index != targetKeys.length - 1 && <span style={{ cursor: "pointer" }} onClick={() => { down(b, index) }}>下移</span>} &nbsp;
                            {index != 0 && <span style={{ cursor: "pointer" }} onClick={() => { up(b, index) }}>上移</span>} &nbsp;
                            <span style={{ cursor: "pointer" }} onClick={() => { rightEdit(a, b) }}>修改</span> &nbsp;
                            <span style={{ cursor: "pointer" }} onClick={() => { rightDel(a, b) }}>删除</span> &nbsp;
                        </p>
                    </>
                )
            }
        },
    ];
    const [targetKeys, setTargetKeys] = useState<any[]>(originTargetKeys);
    const [isopen, setisOpen] = useState(false)
    const [val, setVal] = useState({
        name: "",
        link: ""
    })
    const [form] = Form.useForm();
    const onChange = (nextTargetKeys: string[]) => {
        setTargetKeys(nextTargetKeys);
    };
    // right
    const down = (b: any, index: any) => {
        const newArr = [...targetKeys];
        const ind = targetKeys.indexOf(b.key);
        let tep = newArr[ind];
        newArr[ind] = newArr[ind + 1];
        newArr[ind + 1] = tep;
        setTargetKeys(newArr);

    }
    const up = (b: any, index: any) => {
        const newArr = [...targetKeys];
        const ind = targetKeys.indexOf(b.key);
        let tep = newArr[ind];
        newArr[ind] = newArr[ind - 1];
        newArr[ind - 1] = tep;
        setTargetKeys(newArr);
    }
    const rightEdit = (a: any, b: any) => {
        edit(a, b)
    }
    const rightDel = (a: any, b: any) => {
        del(a, b)
    }
    // left
    const edit = (a: any, b: any) => {
        setisOpen(true)
        setIsedit(true)
        setIsKey(b.key)
        form.setFieldsValue({
            yunyinImg: [
                {
                    uid: 1,
                    key: b.title.imgKey,
                    url: b.title.imgUrl,
                }
            ],
            yunyinName: b.title.name,
            yunyinLink: b.title.link
        })
    }
    const del = (a: any, b: any) => {
        let delData = data.filter((ele: any) => ele.key !== b.key)
        setData(delData)
    }
    const open = () => {
        setisOpen(true)
        form.setFieldsValue({
            yunyinImg: [],
            yunyinName: "",
            yunyinLink: ""
        })
    }
    const handleOk = async () => {
        let dataTab = await form.validateFields()
        setIsedit(false)
        if (isEdit == true) {
            let updata = {
                key: iskey,
                title: {
                    imgKey: dataTab.yunyinImg[0].response ? dataTab.yunyinImg[0].response.data.imgKey : dataTab.yunyinImg[0].key,
                    imgUrl: dataTab.yunyinImg[0].response ? dataTab.yunyinImg[0].response.data.imgUrl : dataTab.yunyinImg[0].url,
                    link: dataTab.yunyinLink,
                    name: dataTab.yunyinName,
                }
            }
            let newArr = [...data]
            let obj = { ...updata }
            let index = data.findIndex((ele: any) => ele.key == iskey)
            newArr[index] = obj
            setData(newArr)
        } else {
            mockData.push({
                key: Date.now(),
                title: {
                    imgUrl: dataTab.yunyinImg[0].response.data.imgUrl,
                    imgKey: dataTab.yunyinImg[0].response.data.imgKey,
                    name: dataTab.yunyinName,
                    link: dataTab.yunyinLink
                }
            })
            setData(mockData);
        }
        setisOpen(false);

        console.log(dataTab, "dataTab")
    };
    const handleCancel = () => {
        setIsedit(false)
        setVal({
            ...val,
            name: "",
            link: ""
        })
        setisOpen(false);
    };
    const normFileActiveImg = (e: any) => {
        if (Array.isArray(e)) {
            return e;
        }
        e.fileList = e.fileList.slice(-1);
        return e?.fileList;
    };
    const changeName = (e: any) => {
        setVal({
            ...val,
            name: e.target.value
        })
    }
    const changeLink = (e: any) => {
        setVal({
            ...val,
            link: e.target.value
        })
    }
    useEffect(() => {
        setData(mockData)
    }, [])
    return (
        <div style={{ marginTop: "30px" }}>
            <Button
                style={{
                    margin: "10px 500px",
                    borderRadius: "5px"
                }}
                onClick={open}
                type="primary">新增运营位</Button>
            <TableTransfer
                dataSource={data}
                targetKeys={targetKeys}
                onChange={onChange}
                leftColumns={leftTableColumns}
                rightColumns={rightTableColumns}
            />
            <Modal title="新增" visible={isopen} onOk={handleOk} onCancel={handleCancel}>
                <Form form={form}>
                    <Form.Item
                        name="yunyinImg"
                        label="运营位图片"
                        rules={[{ required: true, message: '请上传运营位图片' }]}
                        valuePropName="fileList"
                        getValueFromEvent={normFileActiveImg}
                        extra="格式限制：png,jpg,jpeg,gif,mp4"
                    >
                        <Upload
                            listType="picture-card"
                            name='multipartFile'
                            action='/campus/campusweb/upload/pictureUpload'
                        >
                            上传
                        </Upload>
                    </Form.Item>
                    <Form.Item
                        name="yunyinName"
                        label="运营位名称"
                        rules={[{ required: true, message: '请输入运营位名称' }]}>
                        <Input placeholder='请输入' onChange={changeName} maxLength={20} value={val.name} />
                    </Form.Item>
                    <Form.Item
                        name="yunyinLink"
                        label="运营位链接"
                    >
                        <Input placeholder='请输入' onChange={changeLink} value={val.link} />
                    </Form.Item>
                    <Form.Item>
                        <div style={{ marginLeft: '80px' }}>
                            <Button onClick={handleCancel}>
                                取消
                            </Button>
                            <Button onClick={handleOk} style={{ marginLeft: '30px' }} type="primary" htmlType="submit">
                                确定
                            </Button>
                        </div>
                    </Form.Item>
                </Form>
            </Modal>
        </div>
    );
};

export default App;